<template>
	<div id="app">
		<!-- 全局加载界面 -->
		<div v-if="globalData.isLoading" class="global-loading">
			<div class="loading-content">
				<div class="game-logo">五绝传说</div>
				<div class="loading-progress">
					<div class="progress-bar">
						<div class="progress-fill" :style="{width: globalData.loadingProgress + '%'}"></div>
					</div>
					<div class="loading-text">{{ globalData.loadingText }}</div>
				</div>
			</div>
		</div>
		
    	<!-- 页面直接切换 -->
		<component v-else :is="currentComponent" :key="currentRoute" ref="pageRef" />
		
		<!-- 全局消息提示 -->
		<GlobalMessage ref="globalMessage" />
	</div>
</template>

<script>
import Navigation from './utils/navigation'
// 导入页面组件 - 使用uni-app标准pages目录
import LoginPage from '../pages/login/index.vue'
import MainPage from '../pages/main/index.vue'
import BattlePage from '../pages/battle/index.vue'
import RoleSelectPage from '../pages/role-select/index.vue'
import SectSelectPage from '../pages/sect/select.vue'
import SectIndexPage from '../pages/sect/index.vue'
import SectSkillsPage from '../pages/sect/skills.vue'
import AttributePage from '../pages/attribute/attribute.vue'
import SkillPage from '../pages/skill/skill.vue'
import SkillDetailPage from '../pages/skill/detail.vue'
import SkillEquipPage from '../pages/skill/equip.vue'
import QuestIndexPage from '../pages/quest/index.vue'
import QuestDetailPage from '../pages/quest/detail.vue'
import QuestMapPage from '../pages/quest/map.vue'
import QuestDialoguePage from '../pages/quest/dialogue.vue'
import PartnerIndexPage from '../pages/partner/index.vue'
import PartnerDetailPage from '../pages/partner/detail.vue'
import PartnerRecruitPage from '../pages/partner/recruit.vue'
import PartnerFormationPage from '../pages/partner/formation.vue'
// Tabbar页面组件
import AdventurePage from '../pages/adventure/index.vue'
import OpportunityPage from '../pages/opportunity/index.vue'
import MarketPage from '../pages/market/index.vue'
import MarketEquipmentPage from '../pages/market/equipment.vue'
import MarketItemPage from '../pages/market/items.vue'
import SystemPage from '../pages/system/index.vue'
import ActivityIndexPage from '../pages/activity/index.vue'
// 活动子页面
import ActivityLoginPage from '../pages/activity/login.vue'
import ActivityAchievementPage from '../pages/activity/achievement.vue'
import ActivityLevelPage from '../pages/activity/level.vue'
import ActivityMonthlyPage from '../pages/activity/monthly.vue'
import ActivityNewbiePage from '../pages/activity/newbie.vue'
import AdventureMainListPage from '../pages/adventure/mainlist.vue'
import FeedbackPage from '../pages/feedback/index.vue'
// 新增：打造页面
import ForgePage from '../pages/equipment/forge.vue'
import RankPage from '../pages/rank/index.vue'
// 全局消息组件
import GlobalMessage from './components/GlobalMessage.vue'


export default {
	components: {
		LoginPage,
		MainPage,
		BattlePage,
		RoleSelectPage,
		SectSelectPage,
		SectIndexPage,
		SectSkillsPage,
		AttributePage,
		SkillPage,
		SkillDetailPage,
		SkillEquipPage,
		QuestIndexPage,
		QuestDetailPage,
		QuestMapPage,
		QuestDialoguePage,
		PartnerIndexPage,
		PartnerDetailPage,
		PartnerRecruitPage,
		PartnerFormationPage,
		// Tabbar页面组件
		AdventurePage,
		OpportunityPage,
		MarketPage,
		MarketItemPage,
		MarketEquipmentPage,
		SystemPage,
		ActivityIndexPage,
		// 活动子页面组件
		ActivityLoginPage,
		ActivityAchievementPage,
		ActivityLevelPage,
		ActivityMonthlyPage,
		ActivityNewbiePage,
		AdventureMainListPage,
		FeedbackPage,
		ForgePage,
		RankPage,
		GlobalMessage,
	},
	
	data() {
		return {
			// 当前显示的组件
			currentComponent: 'LoginPage',
			
			// 全局数据
			globalData: {
				// 加载状态
				isLoading: true,
				loadingText: '初始化游戏...',
				loadingProgress: 0,
				
				// 基础配置
				baseUrl: 'http://localhost:8000',
				
				// 用户信息
				userInfo: null,
				
				// 角色信息
				roleInfo: null
			}
		}
	},
	
	computed: {
		// 当前路由，用于页面切换动画的key
		currentRoute() {
			return this.currentComponent
		}
	},
	
	mounted() {
		// 监听资源加载完成事件
		this.listenResourcesLoaded()
		// 监听hash变化
		this.listenHashChange()
		// 初始化路由
		this.initRoute()
		// 挂载全局消息方法到window对象
		this.setupGlobalMessage()
	},
	methods: {
		/**
		 * 设置全局消息方法
		 */
		setupGlobalMessage() {
			const self = this
			window.showMessage = function(text, type = 'error', duration = 3000) {
				if (self.$refs.globalMessage) {
					self.$refs.globalMessage.show(text, type, duration)
				}
			}
		},
		/**
		 * 监听资源加载完成事件
		 */
		listenResourcesLoaded() {
			window.addEventListener('resourcesLoaded', () => {
				// 资源加载完成，开始初始化应用
				this.initializeApp()
			})
		},
		
		/**
		 * 初始化应用
		 */
		initializeApp() {
			// 直接设置为100%完成，跳过等待时间
			this.globalData.loadingProgress = 100
			this.globalData.loadingText = '启动完成！'
			
			// 立即检查登录状态并关闭加载界面
			this.checkLoginStatus()
			this.globalData.isLoading = false
		},
		
		/**
		 * 检查登录状态
		 */
		checkLoginStatus() {
			const yid = (typeof uni !== 'undefined' ? uni.getStorageSync('yid') : localStorage.getItem('yid'))
			const userId = (typeof uni !== 'undefined' ? uni.getStorageSync('userId') : localStorage.getItem('userId'))
			const roleId = (typeof uni !== 'undefined' ? uni.getStorageSync('role_id') : localStorage.getItem('role_id'))
			
			if (yid && userId && roleId) {
				// 已登录且已选择角色，直接跳转到主页面
				window.location.hash = '/pages/main/index'
			} else if (yid && userId) {
				// 已登录但未选择角色，跳转到角色选择页面
				window.location.hash = '/pages/role-select/index'
			} else {
				// 未登录，显示登录页
				window.location.hash = '/pages/login/index'
			}
		},
		
		/**
		 * 监听hash变化
		 */
		listenHashChange() {
			window.addEventListener('hashchange', () => {
				this.updateCurrentComponent()
			})
		},
		
		/**
		 * 初始化路由
		 */
		initRoute() {
			this.updateCurrentComponent()
		},
		
		/**
		 * 根据hash更新当前组件
		 */
		updateCurrentComponent() {
			const rawHash = window.location.hash || ''
			const safeHash = rawHash.startsWith('#') ? rawHash : `#${rawHash}`
			// 仅使用纯路径进行路由匹配，剥离查询串
			const routeKey = safeHash.split('?')[0]
			const routeMap = {
				'#/pages/login/index': 'LoginPage',
				'#/pages/main/index': 'MainPage',
				'#/pages/battle/index': 'BattlePage',
				'#/pages/role-select/index': 'RoleSelectPage',
				'#/pages/sect/select': 'SectSelectPage',
				'#/pages/sect/index': 'SectIndexPage',
				'#/pages/sect/skills': 'SectSkillsPage',
				'#/pages/attribute/attribute': 'AttributePage',
				'#/pages/skill/skill': 'SkillPage',
				'#/pages/skill/detail': 'SkillDetailPage',
				'#/pages/skill/equip': 'SkillEquipPage',
				'#/pages/quest/index': 'QuestIndexPage',
				'#/pages/quest/detail': 'QuestDetailPage',
				'#/pages/quest/map': 'QuestMapPage',
				'#/pages/quest/dialogue': 'QuestDialoguePage',
				'#/pages/partner/index': 'PartnerIndexPage',
				'#/pages/partner/detail': 'PartnerDetailPage',
				'#/pages/partner/recruit': 'PartnerRecruitPage',
				'#/pages/partner/formation': 'PartnerFormationPage',
				'#/pages/activity/index': 'ActivityIndexPage',
				// 活动子页面路由
				'#/pages/activity/login': 'ActivityLoginPage',
				'#/pages/activity/achievement': 'ActivityAchievementPage',
				'#/pages/activity/level': 'ActivityLevelPage',
				'#/pages/activity/monthly': 'ActivityMonthlyPage',
				'#/pages/activity/newbie': 'ActivityNewbiePage',
				'#/pages/adventure/mainlist': 'AdventureMainListPage',

				// Tabbar页面路由
				'#/pages/main/index': 'MainPage', // 人物页面路径修正
				'#/pages/adventure/index': 'AdventurePage',
				'#/pages/opportunity/index': 'OpportunityPage',
				'#/pages/market/index': 'MarketPage',
				'#/pages/market/items': 'MarketItemPage',
				'#/pages/market/equipment': 'MarketEquipmentPage',
				'#/pages/system/index': 'SystemPage',
				'#/pages/feedback/index': 'FeedbackPage',
				// 新增：打造页面路由
				'#/pages/equipment/forge': 'ForgePage',
				'#/pages/rank/index': 'RankPage',
			}

			// 默认显示登录页
			this.currentComponent = routeMap[routeKey] || 'LoginPage'

			// 在H5环境中模拟小程序生命周期：为页面注入 onLoad(options)
			this.$nextTick(() => {
				try {
					const params = Navigation.getCurrentParams()
					const vm = this.$refs.pageRef
					if (vm) {
						// 兼容两种写法：组件实例方法或选项中的 onLoad
						const onLoad = (vm.$options && typeof vm.$options.onLoad === 'function') ? vm.$options.onLoad : (typeof vm.onLoad === 'function' ? vm.onLoad : null)
						if (onLoad) {
							onLoad.call(vm, params)
						}
					}
				} catch (e) {
					console.warn('onLoad 参数注入失败:', e)
				}
			})
		}
	}
}
</script>

<style>
/* 全局样式 */
* {
	box-sizing: border-box;
	margin: 0;
	padding: 0;
}

body {
	font-family: 'PingFang SC', 'Helvetica Neue', Helvetica, Arial, sans-serif;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	min-height: 100vh;
}

#app {
	width: 100%;
	min-height: 100vh;
}

.page-container {
	width: 100%;
	min-height: 100vh;
}

/* 全局加载样式 */
.global-loading {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 9999;
	display: flex;
	align-items: center;
	justify-content: center;
}

.loading-content {
	background: rgba(0, 0, 0, 0.8);
	border-radius: 16px;
	padding: 40px;
	display: flex;
	flex-direction: column;
	align-items: center;
	border: 2px solid rgba(255, 255, 255, 0.1);
}

.game-logo {
	font-size: 48px;
	font-weight: bold;
	color: #ffffff;
	margin-bottom: 30px;
	text-shadow: 2px 2px 4px rgba(0,0,0,0.5);
	letter-spacing: 2px;
}

.progress-bar {
	width: 300px;
	height: 8px;
	background: rgba(255, 255, 255, 0.2);
	border-radius: 4px;
	margin: 20px 0 10px 0;
	overflow: hidden;
}

.progress-fill {
	height: 100%;
	background: linear-gradient(90deg, #00d4ff, #007AFF);
	border-radius: 4px;
	transition: width 0.3s ease;
}

.progress-text {
	color: #ffffff;
	font-size: 14px;
	opacity: 0.8;
}

.loading-text {
	font-size: 16px;
	color: #ffffff;
	margin-bottom: 20px;
	opacity: 0.9;
}

/* 通用样式类 */
.container {
	padding: 20px;
}

.card {
	background: rgba(255, 255, 255, 0.95);
	border-radius: 16px;
	padding: 20px;
	margin-bottom: 20px;
	box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.btn {
	padding: 12px 24px;
	border: none;
	border-radius: 8px;
	font-size: 16px;
	cursor: pointer;
	transition: all 0.3s;
}

.btn-primary {
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	color: #ffffff;
}

.btn-primary:hover {
	transform: translateY(-2px);
	box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.text-center {
	text-align: center;
}

.text-primary {
	color: #667eea;
}

.text-secondary {
	color: #666666;
}

.mb-1 { margin-bottom: 8px; }
.mb-2 { margin-bottom: 16px; }
.mb-3 { margin-bottom: 24px; }

/* 页面切换动画已移除 - 实现直接切换 */

.mb-4 { margin-bottom: 32px; }

.mt-1 { margin-top: 8px; }
.mt-2 { margin-top: 16px; }
.mt-3 { margin-top: 24px; }
.mt-4 { margin-top: 32px; }
</style>